<template>
  <div id="admin-manage" class="page-wrapper">
    <h1 class="main-title">电表充值管理</h1>
    <div class="selector-wrapper main-card wrapper">
      <div class="main-card">
        <el-form class="form" :inline="true" ref="form" :model="selectorData">
          <GroupSelector :selectorData="selectorData" />
        </el-form>
      </div>
      <el-button type="primary" @click="onSubmit">获取数据</el-button>
    </div>

    <!-- 表格 -->
    <h1 class="main-title">设备列表</h1>
    <div class="wrapper main-card">
      <div>
        <el-table :data="pageData" style="width: 100%">
          <el-table-column prop="SS_MC" label="房间号"> </el-table-column>
          <el-table-column prop="meterNumber" label="设备编号">
          </el-table-column>
          <el-table-column prop="master_id" label="住户类型"> </el-table-column>
          <el-table-column prop="master_id" label="主控编号"> </el-table-column>
          <!-- <el-table-column prop="region" label="楼栋"> </el-table-column> -->

          <el-table-column prop="totalMoney" label="账户总额">
          </el-table-column>
          <el-table-column prop="depositMoney" label="存款余额">
          </el-table-column>
          <el-table-column
            prop="subsidyMoney"
            label="补助余额"
          ></el-table-column>

          <el-table-column label="电器状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="1"
                inactive-value="0"
                @change="handleSwitchChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="meterRead"
            label="电表读数(度)"
          ></el-table-column>
          <el-table-column
            prop="lastRead"
            label="上次电表读数(度)"
          ></el-table-column>
          <el-table-column property="updatedAt" label="用表日期">
            <template slot-scope="scope">
              {{ formatDate(scope.row.updatedAt) }}
            </template></el-table-column
          >
          <el-table-column property="button" label="操作" width="180">
            <template slot-scope="scope">
              <!-- <el-button @click="modify(scope.row)">缴费</el-button> -->
              <el-button @click="openPaymentDialog(scope.row)">缴费</el-button>

              <el-button @click="modify(scope.row)">退费</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 表格 -->

    <!-- 弹出层内容 -->
    <el-dialog
      title="缴费信息"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form :model="currentItem">
        <el-form-item label="房间号" :label-width="formLabelWidth">
          <el-input
            v-model="currentItem.SS_MC"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="设备余额" :label-width="formLabelWidth">
          <el-input
            v-model="currentItem.balance"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="充值金额" :label-width="formLabelWidth">
          <el-input
            v-model="currentItem.rechargeAmount"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="换算电量" :label-width="formLabelWidth">
          <el-input
            v-model="currentItem.convertedElectricity"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmPayment"
          >确 定 缴 费</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { meterrechargemanage } from '@/api/recharge'
import GroupSelector from './components/all-device.vue'
import { addmasters, getmasters } from '@/api/meter'
import { upmeter, getAllmeter } from '@/api/meter'
export default {
  name: 'RoomInfo',
  components: {
    GroupSelector
  },
  data() {
    return {
      dialogVisible: false,
      currentItem: {},
      formLabelWidth: '120px',
      currentPage: 1,
      pageData: [],
      total: '',
      pageSize: 10,
      selectorData: {
        name: '001',
        buildingId: null,
        floorId: null,
        roomId: null
      },

      tableData: []
    }
  },
  mounted() {
    // this.fetchData()
    this.meterrechargemanage()
  },
  methods: {
    formatDate(isoString) {
      const date = new Date(isoString)
      const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }
      return date.toLocaleString('zh-CN', options)
    },
    handleSwitchChange(row) {
      console.log(row)
      upmeter(row).then(res => {
        console.log(res.data.result.state)
        if (res.data.result.state === '1') {
          this.$message.success('开关已打开')
        } else {
          this.$message.warning('开关已关闭')
        }
      })
    },
    openPaymentDialog(item) {
      // 设置当前选中项的信息
      this.currentItem = {
        roomNumber: item.master_id, // 假设master_id是房间号
        balance: item.layer, // 假设balance是设备余额
        rechargeAmount: '', // 初始化充值金额
        convertedElectricity: '0' // 初始化换算电量
      }
      // 显示弹出层
      this.dialogVisible = true
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    confirmPayment() {
      // 这里编写确认缴费的逻辑
      // 例如，发送请求到后端进行缴费处理
      console.log('确认缴费，充值金额：', this.currentItem.rechargeAmount)
      // 关闭弹出层
      this.dialogVisible = false
    },
    // 分页逻辑
    queryByPage() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = this.currentPage * this.pageSize
      return this.tableData.slice(start, end)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.pageData = this.queryByPage()
    },
    handleCurrentChange(val) {
      console.log(val)
      this.currentPage = val
      this.pageData = this.queryByPage()
    },
    // 获取服务器数据
    fetchData() {
      getmasters().then(res => {
        console.log(res)
        this.tableData = res.data.master
        this.total = res.data.master.length // 设置总数据量
        this.pageData = this.queryByPage() // 初始化分页数据
      })
    },
    onSubmit() {
      this.meterrechargemanage(this.selectorData)
    },
    meterrechargemanage(data) {
      meterrechargemanage(data)
        .then(res => {
          console.log(res.data)
          this.tableData = res.data
          this.total = res.data.length // 设置总数据量
          this.pageData = this.queryByPage() // 初始化分页数据
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleSwitchChange(row) {
      // 构建请求数据
      console.log(row)
      const requestData = {
        buildingId: row.buildingId,
        floorId: row.floorId,
        roomId: row.roomId,
        // 根据你的接口文档，你可能需要传递以下字段
        // meterNumber: row.meterNumber, // 假设这是设备编号
        state: row.state // 当前行的状态
        // ...其他可能需要的字段
      }

      meterrechargemanage(requestData)
        .then(response => {
          // 处理成功响应
          console.log('状态更新成功', response)
          // 这里可以添加成功提示，例如使用Element UI的Message组件
          this.$message({
            type: 'success',
            message: '设备状态更新成功!'
          })
        })
        .catch(error => {
          // 处理错误响应
          console.error('状态更新失败', error)
          // 这里可以添加错误提示
          this.$message({
            type: 'error',
            message: '设备状态更新失败!'
          })
          // 如果更新失败，可能需要将开关状态恢复到原始状态
          row.state = row.state === '1' ? '0' : '1'
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  margin: 40px 0;
}

.selector-wrapper {
  display: flex;
  flex-direction: e;
  justify-content: space-between;
  align-items: center;
  /* 垂直居中 */
}

.list-wrapper {
  margin-top: 40px;
}

.el-form-item--small.el-form-item {
  display: flex;
  align-items: center;
}
.el-form form el-form--inline {
  display: flex;
  align-items: center;
}
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  /* Adjust margin as needed */
}
</style>
